package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.constant.CommonConstant;
import com.ruoyi.system.constant.ExceptionConstant;
import com.ruoyi.system.domain.OrderInitiate;
import com.ruoyi.system.domain.OrderLink;
import com.ruoyi.system.domain.OrderLinkRealize;
import com.ruoyi.system.mapper.OrderInitiateMapper;
import com.ruoyi.system.mapper.OrderLinkMapper;
import com.ruoyi.system.mapper.OrderLinkRealizeMapper;
import com.ruoyi.system.mapper.OrderOperationMapper;
import com.ruoyi.system.service.IOrderInitiateService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-09
 */
@Service
public class OrderInitiateServiceImpl implements IOrderInitiateService {
    private static final Logger log = LoggerFactory.getLogger(OrderInitiateServiceImpl.class);

    private final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    @Autowired
    private OrderInitiateMapper orderInitiateMapper;

    @Autowired
    private OrderLinkMapper orderLinkMapper;

    @Autowired
    private OrderLinkRealizeMapper orderLinkRealizeMapper;

    @Autowired
    private OrderOperationMapper orderOperationMapper;

    /**
     * 查询订单信息
     *
     * @param id 订单信息主键
     * @return 订单信息
     */
    @Override
    public OrderInitiate selectOrderInitiateById(Long id) {
        OrderInitiate orderInitiate = orderInitiateMapper.selectOrderInitiateById(id);
        // 查询订单所对应的环节信息
        List<OrderLinkRealize> orderLinkRealizes = orderLinkRealizeMapper.selectOrderLinkRealizeList(orderInitiate.getOrderId());
        if (ObjectUtils.isNotEmpty(orderLinkRealizes)) {
            List<Long> linkIds = orderLinkRealizes.stream().map(OrderLinkRealize::getLinkId).collect(Collectors.toList());
            // 查询相关联环节的信息
            List<OrderLink> orderLinks = orderLinkMapper.selectOrderLinkByIds(linkIds);
            if (ObjectUtils.isNotEmpty(orderLinks)) {
                // 相关联环节列表map
                Map<Long, OrderLink> orderLinkMap = orderLinks.stream()
                        .collect(Collectors.toMap(OrderLink::getId, s -> s, (key1, key2) -> key1));
                orderLinkRealizes.stream().peek(vo -> {
                    if (ObjectUtils.isNotEmpty(orderLinkMap.get(vo.getLinkId()))) {
                        vo.setLinkName(orderLinkMap.get(vo.getLinkId()).getLinkName());
                    }
                }).collect(Collectors.toList());
            }
            orderInitiate.setOrderLinkRealizeList(orderLinkRealizes);
        }
        return orderInitiate;
    }

    /**
     * 查询订单信息列表
     *
     * @param orderInitiate 订单信息
     * @return 订单信息
     */
    @Override
    public List<OrderInitiate> selectOrderInitiateList(OrderInitiate orderInitiate) {
        List<OrderInitiate> orderInitiates = orderInitiateMapper.selectOrderInitiateList(orderInitiate);
        if (ObjectUtils.isEmpty(orderInitiates)) {
            // 当前列表为空
            return orderInitiates;
        }
        // 获取当前列表数据的所有订单id
        List<Long> orderIds = orderInitiates.stream().map(OrderInitiate::getOrderId).collect(Collectors.toList());
        // 查询订单集合下的所有环节信息
        List<OrderLinkRealize> orderLinkRealizes = orderLinkRealizeMapper.selectOrderLinkRealizeListByOrderIds(orderIds);
        if (ObjectUtils.isEmpty(orderLinkRealizes)) {
            // 当前列表下没有环节信息
            return orderInitiates;
        }
        Map<Long, List<OrderLinkRealize>> longListMap = orderLinkRealizes
                .stream()
                .collect(Collectors.groupingBy(OrderLinkRealize::getOrderId));
        return orderInitiates.stream().map(vo -> {
            List<OrderLinkRealize> orderLinkRealizeList = longListMap.get(vo.getOrderId());
            if (ObjectUtils.isNotEmpty(orderLinkRealizeList)) {
                vo.setOrderLinkRealizeList(orderLinkRealizeList);
            }
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 新增订单信息
     *
     * @param orderInitiate 订单信息
     * @return 结果
     */
    @Override
    public int insertOrderInitiate(OrderInitiate orderInitiate) {
        try {
            // 订单号：格式为年月日时分秒
            long orderId = Long.parseLong(DateFormatUtils.format(new Date(), YYYYMMDDHHMMSS));
            OrderInitiate orderInitiate1 = orderInitiateMapper.selectOrderInitiateById(orderId);
            if (ObjectUtils.isNotEmpty(orderInitiate1)) {
                throw new RuntimeException(ExceptionConstant.ORDER_ID_EXCEPTION);
            }
            initiateOrder(orderInitiate, orderId);
            List<OrderLinkRealize> orderLinkRealizeList = orderInitiate.getOrderLinkRealizeList();
            // 订单表关联的环节流程
            if (ObjectUtils.isNotEmpty(orderLinkRealizeList)) {
                batchInsertOrderLinkRealize(orderLinkRealizeList, orderInitiate.getOrderId());
            }
            // 订单信息表新增
            return orderInitiateMapper.insertOrderInitiate(orderInitiate);
        } catch (Exception e) {
            log.error("FAIL insertOrderInitiate error is:{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 批量新增环节信息
     *
     * @param orderLinkRealizeList 环节信息集合
     * @param orderId 订单id
     */
    public void batchInsertOrderLinkRealize(List<OrderLinkRealize> orderLinkRealizeList, long orderId) {
        List<OrderLinkRealize> orderLinkRealizes = orderLinkRealizeList.stream().map(vo -> {
            vo.setOrderId(orderId);
            initiateOrderLinkRealize(vo);
            return vo;
        }).collect(Collectors.toList());
        orderLinkRealizeMapper.batchInsertOrderLinkRealize(orderLinkRealizes);
    }

    /**
     * 初始化订单信息
     *
     * @param orderInitiate 订单信息
     */
    public void initiateOrder(OrderInitiate orderInitiate, long orderId) {
        orderInitiate.setOrderId(orderId);
        orderInitiate.setCreateTime(DateUtils.getNowDate());
        orderInitiate.setUpdateTime(DateUtils.getNowDate());
        orderInitiate.setCreateBy(SecurityUtils.getUsername());
        orderInitiate.setUpdateBy(SecurityUtils.getUsername());
        orderInitiate.setDeleteFlag(CommonConstant.DELETE_FLAG_N);
    }

    /**
     * 初始化环节信息
     *
     * @param orderLinkRealize 环节信息
     */
    public void initiateOrderLinkRealize(OrderLinkRealize orderLinkRealize) {
        orderLinkRealize.setCreateTime(DateUtils.getNowDate());
        orderLinkRealize.setUpdateTime(DateUtils.getNowDate());
        orderLinkRealize.setFinishNumber(0);
        orderLinkRealize.setLinkStatus(CommonConstant.ZERO);
        orderLinkRealize.setCreateBy(SecurityUtils.getUsername());
        orderLinkRealize.setUpdateBy(SecurityUtils.getUsername());
        orderLinkRealize.setDeleteFlag(CommonConstant.DELETE_FLAG_N);
    }

    /**
     * 修改订单信息
     *
     * @param orderInitiate 订单信息
     * @return 结果
     */
    @Override
    public int updateOrderInitiate(OrderInitiate orderInitiate) {
        try {
            OrderInitiate initiate = orderInitiateMapper.selectOrderInitiateById(orderInitiate.getId());
            if (ObjectUtils.isEmpty(initiate)) {
                throw new RuntimeException(ExceptionConstant.DATA_NOT_FOUND);
            }
            if (CommonConstant.TWO.equals(initiate.getOrderStatus()) || CommonConstant.THREE.equals(initiate.getOrderStatus())) {
                throw new RuntimeException(ExceptionConstant.BEEN_ISSUED_NOT_UPDATE);
            }
            // 判定是否修改环节
            List<OrderLinkRealize> orderLinkRealizeList = orderInitiate.getOrderLinkRealizeList();
            if (ObjectUtils.isNotEmpty(orderLinkRealizeList)) {
                orderLinkRealizeMapper.deleteOrderLinkRealizeByOrderIds(Collections.singletonList(initiate.getOrderId()));
                // 批量新增环节信息
                batchInsertOrderLinkRealize(orderLinkRealizeList, initiate.getOrderId());
            }
            orderInitiate.setUpdateBy(SecurityUtils.getUsername());
            orderInitiate.setUpdateTime(DateUtils.getNowDate());
            return orderInitiateMapper.updateOrderInitiate(orderInitiate);
        } catch (Exception e) {
            log.error("FAIL updateOrderInitiate error is:{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 批量删除订单信息
     *
     * @param ids 需要删除的订单信息主键
     * @return 结果
     */
    @Override
    public int deleteOrderInitiateByIds(Long[] ids) {
        try {
            List<OrderInitiate> orderInitiates = orderInitiateMapper.selectOrderInitiateByIds(ids);
            if (ObjectUtils.isNotEmpty(orderInitiates)) {
                List<Long> orderIds = orderInitiates.stream().map(OrderInitiate::getOrderId).collect(Collectors.toList());
                // 批量删除订单信息下的环节信息
                orderLinkRealizeMapper.deleteOrderLinkRealizeByOrderIds(orderIds);
                // 批量删除订单信息下的业务信息
                orderOperationMapper.deleteOrderOperationByOrderIds(orderIds);
            }
            // 删除订单信息
            return orderInitiateMapper.deleteOrderInitiateByIds(ids);
        } catch (Exception e) {
            log.error("FAIL deleteOrderInitiateByIds error is:{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
    }
}
